<template>
  <el-dialog
    :title="title"
    :visible.sync="innerVisible"
    width="600px"
    @close="handleCancel"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="180px"
    >
      <el-form-item label="项目阶段" prop="maturity">
        <el-select
          placeholder="请选择"
          v-model="form.maturity"
          clearable
          :disabled="editIndex > 0"
        >
          <el-option
            v-for="item in maturityOptions"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="形象进度" prop="workProcess">
        <el-select
          placeholder="请选择"
          v-model="form.workProcess"
          clearable
        >
          <el-option
            v-for="item in workProcessOptions"
            :key="item"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="形象进度描述"
        prop="processDescription"
      >
        <el-input
          v-model="form.processDescription"
          placeholder="请输入项目形象进度"
          type="textarea"
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="是否存在问题" prop="problemFlag">
        <el-radio-group v-model="form.problemFlag">
          <el-radio label="是"></el-radio>
          <el-radio label="否"></el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="问题描述" prop="problemContent">
        <el-input
          v-model="form.problemContent"
          placeholder="请输入问题描述"
          type="textarea"
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="解决措施" prop="solveAdvice">
        <el-input
          v-model="form.solveAdvice"
          placeholder="请输入解决措施"
          type="textarea"
          :rows="3"
        />
      </el-form-item>

      <el-form-item label="进度图片：">
        <div class="upload-container">
          <el-upload
            action=""
            list-type="picture-card"
            :http-request="handleUpload"
            :file-list="mergedFileList"
            :before-upload="beforeUpload"
            :on-remove="handleRemove"
            :on-preview="handlePreview"
            multiple
          >
            <i class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">
              支持 jpg、png、jpeg 格式文件
            </div>
          </el-upload>
        </div>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleConfirm"
        >确定</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import dayjs from 'dayjs'
import {
  maturityOptions,
  workProcessOptions
} from '@/utils/project/data'
import {
  projectStageOptions,
  propertyOptions
} from '@/utils/project/data'
import { STATIC_FILE_URL } from '@/api/config.js'

export default {
  name: 'ProgressDialog',
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    title: {
      type: String,
      default: '填写信息'
    },
    currentData: {
      type: Object
    },
    currentInfo: {
      type: Object
    },
    editIndex: {
      type: Number
    },
    projectName: {
      type: String
    }
  },
  data() {
    return {
      form: {
        createTime: '',
        property: '',
        stage: '',
        workProcess: '',
        problemFlag: '是',
        problemContent: '',
        solveAdvice: '',
        maturity: '',
        progressImages: []
      },
      rules: {
        // maturity: [{ required: true, message: '请选择项目成熟程度', trigger: 'change' }],
        // workProcess: [{ required: true, message: '请输入项目形象进度', trigger: 'blur' }]
      },
      innerVisible: false,
      uploadFileList: [],
      STATIC_FILE_URL
    }
  },
  computed: {
    projectStageOptions() {
      return projectStageOptions
    },
    propertyOptions() {
      return propertyOptions
    },
    maturityOptions() {
      return maturityOptions
    },
    workProcessOptions() {
      return workProcessOptions
    },
    mergedFileList() {
      // 处理已上传的图片
      const uploaded = (this.form.progressImages || []).map(
        (item, idx) => {
          // 判断是否为已上传的图片（有filePath属性）
          if (item.filePath) {
            return {
              name: item.filePath || `image-${idx}`,
              url: `${this.STATIC_FILE_URL}${item.filePath}`,
              uid: `uploaded-${idx}`,
              isUploaded: true,
              filePath: item.filePath,
              originalData: item,
              pkid: item.pkid
            }
          } else if (item instanceof File) {
            // 处理本地File对象
            return {
              name: item.name,
              url: URL.createObjectURL(item),
              uid: `local-${idx}`,
              isUploaded: false,
              raw: item,
              originalData: item
            }
          } else {
            // 处理其他格式的本地文件数据
            return {
              name: item.name || `image-${idx}`,
              url:
                item.url ||
                (item.raw
                  ? URL.createObjectURL(item.raw)
                  : ''),
              uid: `other-${idx}`,
              isUploaded: false,
              raw: item.raw || item,
              originalData: item
            }
          }
        }
      )

      // 处理新上传的文件
      const newFiles = this.uploadFileList.map(
        (file, idx) => {
          return {
            name: file.name,
            url: URL.createObjectURL(file),
            uid: `new-${idx}`,
            raw: file,
            isUploaded: false,
            originalData: file
          }
        }
      )

      return [...uploaded, ...newFiles]
    }
  },
  watch: {
    visible(val) {
      this.innerVisible = val
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate()
      }
      if (!this.currentData) {
        this.form = {
          createTime: '',
          property: '',
          stage: '',
          workProcess: '',
          problemFlag: '是',
          problemContent: '',
          solveAdvice: '',
          maturity: '',
          progressImages: []
        }
        this.uploadFileList = []
      }
    },
    innerVisible(val) {
      this.$emit('update:visible', val)
    },
    currentData: {
      handler(val) {
        if (val) {
          this.form = { ...val }
        }
      },
      deep: true,
      immediate: true
    },
    currentInfo(val) {
      if (val) {
        this.form.maturity = val.maturity || ''
      }
    }
  },
  methods: {
    beforeUpload(file) {
      const isImage =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/jpg'
      if (!isImage) {
        this.$message.error(
          '只能上传jpg/png/jpeg格式的图片!'
        )
        return false
      }
      // const isLt10M = file.size / 1024 / 1024 < 10
      // if (!isLt10M) {
      //   this.$message.error('图片大小不能超过 10MB!')
      //   return false
      // }
      return true
    },
    handleUpload({ file }) {
      if (!file) return
      this.uploadFileList.push(file)
    },
    handleRemove(file) {
      if (file.isUploaded) {
        // 从已上传列表中移除
        const index = this.form.progressImages.findIndex(
          (img) => img.pkid === file.pkid
        )

        const fileIndex =
          this.form.resourceFileInfos.findIndex(
            (img) => img.pkid === file.pkid
          )
        if (index !== -1) {
          // 使用 $set 确保响应式更新
          this.$set(this.form.progressImages, index, null)
          this.form.progressImages.splice(index, 1)
          this.form.resourceFileInfos.splice(fileIndex, 1)
          // 强制更新计算属性
          this.$nextTick(() => {
            this.$forceUpdate()
          })
        }
      } else {
        // 从uploadFileList中移除新上传的文件
        const fileToRemove = file.raw || file.originalData
        this.uploadFileList = this.uploadFileList.filter(
          (f) => f !== fileToRemove
        )
        if (file.url && file.url.startsWith('blob:')) {
          URL.revokeObjectURL(file.url)
        }
      }
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogImageVisible = true
    },
    handleCancel() {
      this.$emit('update:visible', false)
      // 清理数据
      this.uploadFileList = []
    },
    handleChangeImage(file) {
      if (file.raw) {
        this.uploadFileList.push(file.raw)
      }
    },
    handleRemoveImage(file) {
      if (file.isUploaded) {
        // 从已上传列表中移除
        const index = this.form.progressImages.findIndex(
          (img) => img.filePath === file.filePath
        )
        if (index !== -1) {
          this.form.progressImages.splice(index, 1)
        }
      } else {
        // 从uploadFileList中移除新上传的文件
        const fileToRemove = file.raw || file.originalData
        this.uploadFileList = this.uploadFileList.filter(
          (f) => f !== fileToRemove
        )
        if (file.url && file.url.startsWith('blob:')) {
          URL.revokeObjectURL(file.url)
        }
      }
    },
    handleConfirm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          // 强制更新组件，确保计算属性重新计算
          this.$forceUpdate()

          // 使用nextTick确保更新完成后再处理数据
          this.$nextTick(() => {
            // 使用 mergedFileList 来获取最终的图片列表
            const finalImages = this.mergedFileList.map(
              (file) => {
                if (file.isUploaded) {
                  // 已上传的图片
                  return {
                    filePath: file.filePath,
                    pkid: file.pkid,
                    url: file.url,
                    isUploaded: true
                  }
                } else {
                  // 新上传的图片
                  return {
                    raw: file.raw,
                    url: file.url,
                    isUploaded: false
                  }
                }
              }
            )

            const formData = {
              ...this.form,
              progressImages: finalImages
            }

            const date = new Date()
            formData.createTime = dayjs(date).format(
              'YYYY-MM-DD HH:mm:ss'
            )

            this.$emit('confirm', formData)
            this.handleCancel()
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/dialog.scss';

::v-deep .el-input__inner {
  width: 320px !important;
}

.upload-container {
  ::v-deep
    .el-upload-list--picture-card
    .el-upload-list__item {
    width: 100px;
    height: 100px;
  }

  ::v-deep .el-upload--picture-card {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  ::v-deep .el-upload-list__item-actions {
    opacity: 0;
    background-color: rgba(0, 0, 0, 0.5);
    transition: opacity 0.3s;

    &:hover {
      opacity: 1;
    }
  }

  ::v-deep .el-upload-list__item-preview {
    color: #fff;
    font-size: 16px;
  }

  ::v-deep .el-upload-list__item-thumbnail {
    opacity: 1;
  }
}
</style>
